"""
数据库会话管理
"""
from typing import AsyncGenerator
from sqlalchemy.ext.asyncio import (
    AsyncSession,
    create_async_engine,
    async_sessionmaker
)
from sqlalchemy.orm import declarative_base
from app.core.config import settings
from app.core.logger import app_logger
from fastapi import HTTPException


# 创建异步引擎
engine = create_async_engine(
    settings.DATABASE_URL,
    echo=settings.DB_ECHO,
    pool_size=settings.DB_POOL_SIZE,
    max_overflow=settings.DB_MAX_OVERFLOW,
    pool_recycle=settings.DB_POOL_RECYCLE,
    pool_pre_ping=True,  # 连接前检查
)

# 创建会话工厂
AsyncSessionLocal = async_sessionmaker(
    engine,
    class_=AsyncSession,
    expire_on_commit=False,
    autocommit=False,
    autoflush=False,
)

# 声明基类
Base = declarative_base()


async def get_db() -> AsyncGenerator[AsyncSession, None]:
    """
    获取数据库会话的依赖项
    用于FastAPI的Depends注入
    """
    async with AsyncSessionLocal() as session:
        try:
            # 将 session 提供给请求处理，调用方负责必要的 commit/rollback
            yield session
        except HTTPException:
            # 业务层主动抛出的 HTTPException（如 404/400），不当作 DB 错误记录
            try:
                await session.rollback()
            except Exception:
                pass
            raise
        except Exception:
            # 仅对真实异常记录为数据库会话错误（包含网络/连接问题等）
            try:
                await session.rollback()
            except Exception:
                pass
            app_logger.exception("数据库会话错误（在请求处理期间）")
            raise
        finally:
            try:
                await session.close()
            except Exception:
                pass


async def init_db():
    """初始化数据库（创建所有表）"""
    async with engine.begin() as conn:
        # 在生产环境使用Alembic迁移，这里仅用于开发测试
        if settings.DEBUG:
            await conn.run_sync(Base.metadata.create_all)
            app_logger.info("数据库表创建完成")


async def close_db():
    """关闭数据库连接"""
    await engine.dispose()
    app_logger.info("数据库连接已关闭")

